package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.minio.MinioProperties;
import com.atguigu.lease.web.admin.service.FileService;
import io.minio.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {
    @Autowired
    private MinioClient minioClient;

    @Autowired
    private MinioProperties minioProperties;
    @Override
    public String upFile(MultipartFile file) throws Exception{
        //判断是否有桶
        boolean is = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build());

        //如果没桶，创建桶并设置权限
        if (!is) {

            //创建桶
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());

            //设置权限
            String policy = """
                    {
                      "Statement" : [ {
                        "Action" : "s3:GetObject",
                        "Effect" : "Allow",
                        "Principal" : "*",
                        "Resource" : "arn:aws:s3:::%s/*"
                      } ],
                      "Version" : "2012-10-17"
                    }""".formatted(minioProperties.getBucketName());

            minioClient.setBucketPolicy(SetBucketPolicyArgs.builder().bucket(minioProperties.getBucketName()).config(policy).build());
        }

        //设置日期，使桶中文件更加工整
        String date = new SimpleDateFormat("yyyyMMdd").format(new Date());
        //设置uuid，防止文件重名
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        //设置文件名
        String objeckName = date + "/" + uuid + "_" + file.getOriginalFilename();
        //上传文件
        minioClient.putObject(PutObjectArgs.builder().bucket(minioProperties.getBucketName()).
                //文件名
                 object(objeckName).
                //流
                 stream(file.getInputStream(),file.getSize(),-1).
                //类型
                 contentType(file.getContentType()).
                 build());

        //返回url
        return String.join("/",minioProperties.getEndpoint(),minioProperties.getBucketName(),objeckName);
    }
}
